//
//  GrantChuLiZhongViewController.m
//  FactorySale
//
//  Created by 李 on 2020/3/30.
//  Copyright © 2020 主事丫环. All rights reserved.
//

#import "GrantChuLiZhongViewController.h"
#import "BuZhuJinZheDieCell.h"// 配件信息标题cell
#import "BuZhuJinPeiJianInfoCell.h"// 配件信息内容cell
#import "ShenQingBuZhuJinInfoCell.h"// 申请补助金信息cell
#import "ShenHeViewController.h"// 审核控制器
#import "GrantDetailContentModel.h"
#import "KeHuShouHuoDiZhiCell.h"// 客户售货地址cell
#import "HuiJiChangJiaDiZhiCell.h"// 回寄厂家地址cell
#import "ShenHeFinishedViewController.h"// 已完成控制器
#import "BoHuiAlertView.h"// 驳回弹出框
#import "GrantDetailStatesModel.h"
#import "NegotiationHistoryController.h"
#import "ConfirmSendMonsyAlertController.h"
#import "BalanceModel.h"
#import "IssueNowNoMoneyAlertController.h"
#import "IssueNowAlertController.h"
@interface GrantChuLiZhongViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topNavBarConstraint;
@property (weak, nonatomic) IBOutlet UILabel *timelab;
@property (weak, nonatomic) IBOutlet UITableView *listTableView;
@property (nonatomic,strong) GrantDetailContentModel *detailModel;
@property (nonatomic,strong) GrantDetailStatesModel *statesModel;
// 控制配件信息cell的展开与折叠
@property (nonatomic,assign)BOOL peiJianInfoCellSelected;
@property (nonatomic,strong)BoHuiAlertView *alert;
@property (nonatomic,strong)NSString *refuseStr;

@property (nonatomic,strong)BalanceModel *balanceModel;

@end
static NSString *const BuZhuJinZheDieCellID = @"BuZhuJinZheDieCell";
static NSString *const BuZhuJinPeiJianInfoCellID = @"BuZhuJinPeiJianInfoCell";
static NSString *const ShenQingBuZhuJinInfoCellID = @"ShenQingBuZhuJinInfoCell";
static NSString *const KeHuShouHuoDiZhiCellID = @"KeHuShouHuoDiZhiCell";
static NSString *const HuiJiChangJiaDiZhiCellID = @"HuiJiChangJiaDiZhiCell";

@implementation GrantChuLiZhongViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.topNavBarConstraint.constant = kNaviHeight;
    self.view.backgroundColor = Main_BackGroundColor;
    [self setupTableView];
    [self requestGrantsDetail];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
#pragma mark - 私有方法
-(void)setupTableView {
    [self.listTableView registerClass:[BuZhuJinZheDieCell class] forCellReuseIdentifier:BuZhuJinZheDieCellID];
    [self.listTableView registerClass:[BuZhuJinPeiJianInfoCell class] forCellReuseIdentifier:BuZhuJinPeiJianInfoCellID];
    [self.listTableView registerClass:[ShenQingBuZhuJinInfoCell class] forCellReuseIdentifier:ShenQingBuZhuJinInfoCellID];
    [self.listTableView registerNib:[UINib nibWithNibName:NSStringFromClass([KeHuShouHuoDiZhiCell class]) bundle:nil] forCellReuseIdentifier:KeHuShouHuoDiZhiCellID];
    [self.listTableView registerNib:[UINib nibWithNibName:NSStringFromClass([HuiJiChangJiaDiZhiCell class]) bundle:nil] forCellReuseIdentifier:HuiJiChangJiaDiZhiCellID];
    [self addFooterView];
}
- (IBAction)backBtnClick {
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)historyButtonClick {
    NegotiationHistoryController * vc = [[NegotiationHistoryController alloc] init];
    vc.orderID = self.idStr;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 网络请求
-(void)requestGrantsDetail {
    NSDictionary *param = @{
        @"id":NOTNIL(self.idStr)
    };
    [NetWorkTool POST:grantsDetail param:param success:^(id dic) {
        self.detailModel = [GrantDetailContentModel mj_objectWithKeyValues:dic[@"data"]];
        self.statesModel = [GrantDetailStatesModel mj_objectWithKeyValues:dic[@"data"][@"states"]];
        [self refreshViewsData];
        [self.listTableView reloadData];
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
        
    } fail:^(NSError *error) {
        
    } needUser:NO];
}
-(void)refreshViewsData{
    //    self.statesModel.state = @"1";
    if ([self.statesModel.state isEqualToString:@"1"]) {
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@  商家回复:\n请尽快回寄损坏产品,运费需自己承担",self.statesModel.createTime]];
        NSRange range1 = [[str string] rangeOfString:self.statesModel.createTime];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#333333"] range:range1];
        NSRange range2 = [[str string] rangeOfString:@"商家回复:\n请尽快回寄损坏产品,运费需自己承担"];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#F2A225"] range:range2];
        self.timelab.attributedText = str;
    } else if ([self.statesModel.state isEqualToString:@"3"]){
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@  师傅开始回寄",self.statesModel.createTime]];
        NSRange range1 = [[str string] rangeOfString:self.statesModel.createTime];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#333333"] range:range1];
        NSRange range2 = [[str string] rangeOfString:@"师傅开始回寄"];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:@"#31CEA9"] range:range2];
        self.timelab.attributedText = str;
    }
}

#pragma mark UITableView
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(20, 0, SCREEN_WIDTH-40, 0.5)];
    headerView.backgroundColor = Main_BackGroundColor;
    return headerView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section==0) {
        if (self.peiJianInfoCellSelected ==YES) {
            return 2;
        } else {
            return 1;
        }
        return 1;
    }
    return 1;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            BuZhuJinZheDieCell *cell = [tableView dequeueReusableCellWithIdentifier:BuZhuJinZheDieCellID];
            [cell.zhanKaiBtn addTarget:self action:@selector(zhanKaiBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        } else {
            BuZhuJinPeiJianInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:BuZhuJinPeiJianInfoCellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            cell.model = self.detailModel;
            return cell;
        }
    }
    if (indexPath.section==1) {
        ShenQingBuZhuJinInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:ShenQingBuZhuJinInfoCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.model = self.detailModel;
        return cell;
    }
    if (indexPath.section==2) {
        KeHuShouHuoDiZhiCell *cell = [tableView dequeueReusableCellWithIdentifier:KeHuShouHuoDiZhiCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.detailModel;
        return cell;
    }
    if (indexPath.section==3) {
        HuiJiChangJiaDiZhiCell *cell = [tableView dequeueReusableCellWithIdentifier:HuiJiChangJiaDiZhiCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.arrowBtn.hidden = YES;
        cell.model = self.detailModel;
        return cell;
    }
    NSString *cellIdentifier = @"iden3";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section ==0) {
        if (indexPath.row==0) {
            return 37;
        }
        if (indexPath.row==1) {
            return 335;
        }
    }
    if (indexPath.section ==1) {
        return 185;
    }
    if (indexPath.section ==2) {
        if ([self.statesModel.state isEqualToString:@"1"]) {
            return 0;
        } else {
            return [tableView fd_heightForCellWithIdentifier:KeHuShouHuoDiZhiCellID configuration:^(KeHuShouHuoDiZhiCell * cell) {
                cell.model = self.detailModel;
            }];
        }
    }
    if (indexPath.section ==3) {
        return [tableView fd_heightForCellWithIdentifier:HuiJiChangJiaDiZhiCellID configuration:^(HuiJiChangJiaDiZhiCell * cell) {
            cell.model = self.detailModel;
        }];
    }
    return 0;
}
-(void)zhanKaiBtnClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    UIView *view = [sender superview];
    BuZhuJinZheDieCell *cell = (BuZhuJinZheDieCell *)[view superview];
    if (sender.selected) {
        self.peiJianInfoCellSelected = YES;
        [cell.zhanKaiBtn setImage:[UIImage imageNamed:@"向上"] forState:UIControlStateNormal];
    } else {
        self.peiJianInfoCellSelected = NO;
        [cell.zhanKaiBtn setImage:[UIImage imageNamed:@"向下"] forState:UIControlStateNormal];
    }
    [self.listTableView reloadData];
}

-(void)addFooterView {
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWIDTH, 100)];
    footerView.backgroundColor = Main_BackGroundColor;
    
    UIButton *faFangBut = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [faFangBut setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    faFangBut.frame  = CGRectMake(20, 32, (KWIDTH-20*2-25)/2, 44);
    [faFangBut setBackgroundImage:imgname(@"按钮背景") forState:UIControlStateNormal];
    [faFangBut setTitle:@"补寄新配件，并发放补助金" forState:UIControlStateNormal];
    [faFangBut setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    faFangBut.titleLabel.font = KFontPingFangSCMedium(11);
    faFangBut.layer.masksToBounds = YES;
    faFangBut.layer.cornerRadius = 22;
    [faFangBut addTarget:self action:@selector(faFangButAction) forControlEvents:(UIControlEventTouchUpInside)];
    [footerView addSubview: faFangBut];
    
    UIButton *boHuiBut = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [boHuiBut setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    boHuiBut.frame  = CGRectMake(faFangBut.right+25, 32, (KWIDTH-20*2-25)/2, 44);
    [boHuiBut setBackgroundImage:imgname(@"按钮背景") forState:UIControlStateNormal];
    [boHuiBut setTitle:@"驳回，并寄回原件" forState:UIControlStateNormal];
    [boHuiBut setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    boHuiBut.layer.masksToBounds = YES;
    boHuiBut.layer.cornerRadius = 22;
    boHuiBut.titleLabel.font = KFontPingFangSCMedium(11);
    [boHuiBut addTarget:self action:@selector(boHuiButAction) forControlEvents:(UIControlEventTouchUpInside)];
    [footerView addSubview: boHuiBut];
    
    self.listTableView.tableFooterView = footerView;
}
-(void)faFangButAction {
    ConfirmSendMonsyAlertController * vc = [[ConfirmSendMonsyAlertController alloc] init];
    vc.confirmButtonClick = ^{
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"id"] = self.idStr;
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [NetWorkTool POST:factoryAuditGrants param:param success:^(id dic) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            self.balanceModel = [BalanceModel mj_objectWithKeyValues:dic[@"data"]];
            if ([self.balanceModel.type isEqualToString:@"0"]) {//1可以支付 0余额不足
                // 余额不足
                IssueNowNoMoneyAlertController * vc = [[IssueNowNoMoneyAlertController alloc] init];
                vc.model = self.balanceModel;
                [self presentViewController:vc animated:YES completion:nil];
            } else {
                IssueNowAlertController * vc = [[IssueNowAlertController alloc] init];
                vc.model = self.balanceModel;
                vc.idStr = self.idStr;
                vc.okButtonClick = ^{
                    [self.navigationController popToRootViewControllerAnimated:YES];
                };
                [self presentViewController:vc animated:YES completion:nil];
            }
        } other:^(id dic) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        } fail:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        } needUser:YES];
    };
    [self presentViewController:vc animated:YES completion:nil];
    
}
-(void)boHuiButAction {
    kWeakSelf;
    _alert = [[BoHuiAlertView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH)];
    _alert.reasonTextViewHandle = ^(NSString * _Nonnull text) {
        weakSelf.refuseStr = text;
    };
    _alert.sureBtnHandle = ^{
        
        if (weakSelf.refuseStr.length==0) {
            ShowToastWithText(@"请输入驳回原因");
            return ;
        }
        NSDictionary *param = @{
            @"way":@"3",//审核方式 1 （回寄配件）2 （直接同意）3（驳回）4（回寄后审核通过）
            @"id":NOTNIL(weakSelf.idStr),//补助金id
            @"factoryName":NOTNIL(weakSelf.detailModel.factoryName),//厂家姓名
            @"factoryPhone":NOTNIL(weakSelf.detailModel.factoryPhone),//厂家电话
            @"factoryAddress":NOTNIL(weakSelf.detailModel.factoryAddress),//厂家地址
            @"refuse":NOTNIL(weakSelf.refuseStr),//驳回原因
        };
        [NetWorkTool POST:auditGrants param:param success:^(id dic) {
            
            [weakSelf.alert removeFromSuperview];
            ShenHeFinishedViewController *vc = [[ShenHeFinishedViewController alloc]init];
            vc.idStr = weakSelf.idStr;
            vc.backRootController = YES;
            [weakSelf.navigationController pushViewController:vc animated:YES];
            
            
        } other:^(id dic) {
            ShowToastWithText(dic[@"msg"]);
            
        } fail:^(NSError *error) {
            
        } needUser:NO];
        
    };
    [[UIApplication sharedApplication].keyWindow addSubview:_alert];
    
}
@end


